/**
 * 检测网络状态函数
 */
import user from '@/content/api/user'
const internetAvailable = require("internet-available");

export class Internet {
    constructor(){}

    static checkInternet(domain){
        return new Promise((resolve, reject) => {
            internetAvailable({
                timeout: 5000,
                retries: 3,
                domainName: domain,
                port: 53,
                host: '114.114.114.114'
            }).then(() => {
                resolve(true);
            }).catch(() => {
                reject(false);
            })
        })
    }

    static intervalCheck(enviroment){
        if(window.internetInterval){
            clearInterval(window.internetInterval);
        }

        window.internetInterval = setInterval(function () {
            let domain = "";
            if(enviroment === 'production'){
                domain = "bos.kquestions.com";
            }else {
                domain = "dev.bos.kquestions.com";
            }
            internetAvailable({
                domainName: domain,
                port: 53,
                host: '114.114.114.114'
            }).then(() => {
                localStorage.netStatus = true;
            }).catch(() => {
                localStorage.netStatus = false;
            });
        }, 1000 * 5);
    }

    /**
     * 通过调用接口确定网络连接
     * @param callback
     * @return 0 - 未连网；1-连网但是token过期；2-连网且token不过期
     */
    static checkInternetByInvokeApi(callback){
        user.tick().then((res) => {
            if(callback){
                if(res.code == -1000){
                    callback(1);
                }else{
                    callback(2)
                }
            }
        }).catch(error => {
            console.log("第一次检测网络失败!")
            user.tick().then((res) => {
                if(callback){
                    if(res.code == -1000){
                        callback(1);
                    }else{
                        callback(2)
                    }
                }
            }).catch(error => {
                console.log("第二次检测网络失败!")
                user.tick().then((res) => {
                    if(callback){
                        if(res.code == -1000){
                            callback(1);
                        }else{
                            callback(2)
                        }
                    }
                }).catch(error => {
                    console.log("第三次检测网络失败!");
                    if(callback){
                        callback(0);
                    }
                })
            })
        })
    }
}
